/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.qx.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.qx.entity.QxDataRule;
import com.thinkgem.jeesite.modules.qx.entity.QxLeagueMatches;
import com.thinkgem.jeesite.modules.qx.entity.QxMatch;
import com.thinkgem.jeesite.modules.qx.entity.QxMatchFuture;
import com.thinkgem.jeesite.modules.qx.entity.QxMatchHistory;
import com.thinkgem.jeesite.modules.qx.entity.QxTeam;
import com.thinkgem.jeesite.modules.qx.entity.QxTeamMatch;
import com.thinkgem.jeesite.modules.qx.service.QxDataRuleService;
import com.thinkgem.jeesite.modules.qx.service.QxMatchFutureService;
import com.thinkgem.jeesite.modules.qx.service.QxMatchHistoryService;
import com.thinkgem.jeesite.modules.qx.utils.QxCacheUtils;

/**
 * 单表生成Controller
 * @author zequs
 * @version 2017-09-03
 */
@Controller
@RequestMapping(value = "${adminPath}/qx/qxMatchFuture")
public class QxMatchFutureController extends BaseController {

	@Autowired
	private QxMatchFutureService qxMatchFutureService;
	
	@Autowired
	private QxDataRuleService qxDataRuleService;
	
	@Autowired
	private QxMatchHistoryService qxMatchHistoryService;
	
	@ModelAttribute
	public QxMatchFuture get(@RequestParam(required=false) String id) {
		QxMatchFuture entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = qxMatchFutureService.get(id);
		}
		if (entity == null){
			entity = new QxMatchFuture();
		}
		return entity;
	}
	
	@RequiresPermissions("qx:qxMatchFuture:view")
	@RequestMapping(value = {"list", ""})
	public String list(QxMatchFuture qxMatchFuture, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<QxMatchFuture> page = qxMatchFutureService.findPage(new Page<QxMatchFuture>(request, response), qxMatchFuture); 
		model.addAttribute("page", page);
		return "modules/qx/qxMatchFutureList";
	}

	@RequiresPermissions("qx:qxMatchFuture:view")
	@RequestMapping(value = "form")
	public String form(QxMatchFuture qxMatchFuture, Model model) {
		model.addAttribute("qxMatchFuture", qxMatchFuture);
		return "modules/qx/qxMatchFutureForm";
	}

	@RequiresPermissions("qx:qxMatchFuture:edit")
	@RequestMapping(value = "save")
	public String save(QxMatchFuture qxMatchFuture, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, qxMatchFuture)){
			return form(qxMatchFuture, model);
		}
		qxMatchFutureService.save(qxMatchFuture);
		addMessage(redirectAttributes, "保存单表成功");
		return "redirect:"+Global.getAdminPath()+"/qx/qxMatchFuture/?repage";
	}
	
	@RequiresPermissions("qx:qxMatchFuture:edit")
	@RequestMapping(value = "delete")
	public String delete(QxMatchFuture qxMatchFuture, RedirectAttributes redirectAttributes) {
		qxMatchFutureService.delete(qxMatchFuture);
		addMessage(redirectAttributes, "删除单表成功");
		return "redirect:"+Global.getAdminPath()+"/qx/qxMatchFuture/?repage";
	}

	/**
     * 导入即将比赛赛事数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("qx:qxMatchFuture:excel")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        if(Global.isDemoMode()){
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:"+Global.getAdminPath()+"/qx/qxMatchFuture/?repage";
        }
        try {
            int failureNum = 0;
            int successNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<QxMatchFuture> list = ei.getDataList(QxMatchFuture.class);
            List<String>  qxMatchIds = Lists.newArrayList();
            List<QxDataRule> rules = qxDataRuleService.findList(new QxDataRule());
            Map<String, QxDataRule> rulesMap = Maps.uniqueIndex(rules, new Function<QxDataRule, String>() {
                @Override
                public String apply(QxDataRule input) {
                    return input.getLeagueid();
                }
            });  
            for (QxMatchFuture matchFuture : list){
                if (StringUtils.isBlank(matchFuture.getGuestTeamName())
                        || StringUtils.isBlank(matchFuture.getGuestTeamName())) {
                    failureNum++;
                } else {
                    successNum++;
                    QxTeam mainTeam = QxCacheUtils.geTeamByName(matchFuture.getMainTeamName());
                    QxTeam guestTeam = QxCacheUtils.geTeamByName(matchFuture.getGuestTeamName());
                    QxLeagueMatches qxLeagueMatches = QxCacheUtils.getQxLeagueMatches(mainTeam.getLeagueid());
                    matchFuture.setLeagueId(qxLeagueMatches.getId());
                    matchFuture.setMainTeamId(mainTeam.getId());
                    matchFuture.setGuestTeamId(guestTeam.getId());
                    matchFuture.setResult(mainTeam.getRank()<guestTeam.getRank()?1:3);
                    successNum++;
                    Map<String, Object> map = Maps.newHashMap();
                    map = matchEvaluate(matchFuture, rulesMap.get(mainTeam.getLeagueid()));
                    boolean normalVigilance = (Boolean) map.get("normalVigilance");
                    boolean seriousVigilance = (Boolean) map.get("seriousVigilance");
                    StringBuffer normalRute = (StringBuffer) map.get("normalRute");
                    StringBuffer seriousRute = (StringBuffer) map.get("seriousRute");
                    int mainStrength = mainTeam.getStrength();
                    int guestStrength = guestTeam.getStrength();
                    if (mainStrength == guestStrength && mainStrength != 0) {
                        matchFuture.setRecommendType(5);
                        if (mainStrength == 1) {
                            matchFuture.setUnknownReason("强队对强队");
                        } else if (mainStrength == 2) {
                            matchFuture.setUnknownReason("中队对中队");
                        } else if (mainStrength == 3) {
                            matchFuture.setUnknownReason("弱队对弱队");
                        }
                    } else if ((mainStrength == 1 && guestStrength == 3 && !seriousVigilance && !normalVigilance) 
                            || (mainStrength == 3 && guestStrength == 1 && !seriousVigilance && !normalVigilance)) {
                        matchFuture.setRecommendType(1);
                    } else if ((mainStrength == 1 && guestStrength == 3 && !seriousVigilance && normalVigilance) 
                            || (mainStrength == 3 && guestStrength == 1 && !seriousVigilance && normalVigilance)
                            || (mainStrength == 3 && guestStrength == 2 && !seriousVigilance && normalVigilance)
                            || (mainStrength == 2 && guestStrength == 3 && !seriousVigilance && normalVigilance)
                            ) {
                        matchFuture.setRecommendType(2);
                    } else if ((mainStrength == 1 && guestStrength == 2 && !seriousVigilance && normalVigilance) 
                            || (mainStrength == 1 && guestStrength == 1 && !seriousVigilance && normalVigilance)
                            ) {
                        matchFuture.setRecommendType(3);
                    } else if ((mainStrength == 1 && guestStrength == 2 && seriousVigilance) 
                            || (mainStrength == 2 && guestStrength == 1 && seriousVigilance)
                            || (mainStrength == 3 && guestStrength == 2 && seriousVigilance)
                            || (mainStrength == 2 && guestStrength == 3 && seriousVigilance)
                            ) {
                        matchFuture.setRecommendType(4);
                    }
                    matchFuture.setSeriousVigilance(seriousRute.toString());
                    matchFuture.setNormalVigilance(normalRute.toString());
                }
            }
            if (failureNum>0){
                failureMsg.append("，失败 "+failureNum+" 条数据，导入信息如下：");
            }
            addMessage(redirectAttributes, "已成功导入 "+successNum+" 条数据"+failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
        }
        return "redirect:"+Global.getAdminPath()+"/qx/qxMatchFuture/?repage";
    }
    
    public Map<String, Object> matchEvaluate(QxMatchFuture matchFuture, QxDataRule qxDataRule) {
        QxTeam mainTeam = QxCacheUtils.geTeamByName(matchFuture.getMainTeamName());
        QxTeam guestTeam = QxCacheUtils.geTeamByName(matchFuture.getGuestTeamName());
        QxLeagueMatches league = QxCacheUtils.getQxLeagueMatches(mainTeam.getLeagueid());
        StringBuffer sBuffer = new StringBuffer();
        Map<String, Object> map = Maps.newHashMap();
        if (matchFuture.getResult() == 1) {
            map = rute(mainTeam, guestTeam, qxDataRule, matchFuture);
        } else {
            map = rute(guestTeam, mainTeam, qxDataRule, matchFuture);
        }
        return map;
    }
    
    private StringBuffer join(StringBuffer sBuffer , String join) {
        if (sBuffer.length() != 0) {
            sBuffer.append("," + join);
        } else {
            sBuffer.append(join);
        }
        return sBuffer;
    }
    
    private Map<String, Object> rute(QxTeam mainTeam, QxTeam guestTeam, QxDataRule qxDataRule, QxMatchFuture matchFuture) {
        StringBuffer sBuffer = new StringBuffer();
        Map<String, Object> map = Maps.newHashMap(); 
        boolean normalVigilance = false;
        boolean seriousVigilance = false;
        if (mainTeam.getNormalUnusual()*100 > qxDataRule.getUnusualTotal()*100/qxDataRule.getCountTotal()) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("异常状态").getId());
            normalVigilance = true;
        };
        if (mainTeam.getWinCount()*100/mainTeam.getCount() > qxDataRule.getWinCount()*100/qxDataRule.getCountTotal()) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("胜率偏低").getId());
            normalVigilance = true;
        }
        if (guestTeam.getLoseCount()*100/guestTeam.getCount() < qxDataRule.getLoseCount()*100/qxDataRule.getCountTotal()) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("负率太低").getId());
            normalVigilance = true;
        }
        if (mainTeam.getWinScoreTotal()*100/mainTeam.getCount() < qxDataRule.getWinScoreTotal()*100/qxDataRule.getCountTotal()) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("均净胜球少").getId());
            normalVigilance = true;
        }
        if (guestTeam.getLoseScoreTotal()*100/guestTeam.getCount() < qxDataRule.getLoseScoreTotal()*100/qxDataRule.getCountTotal()) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("均净失球少").getId());
            normalVigilance = true;
        }
        QxMatchHistory qxMatchHistoryVO = new QxMatchHistory();
        qxMatchHistoryVO.setTeamid(guestTeam.getId());
        List<QxMatchHistory> loseMatch = qxMatchHistoryService.findList(qxMatchHistoryVO);
        int mainCount = 0; //主场不败
        int guestCount = 0; //客场不败
        for (QxMatchHistory qxMatchHistory : loseMatch) {
            if ((qxMatchHistory.getResult() == 1 || qxMatchHistory.getResult() == 2) && qxMatchHistory.getHomeType() == 0) {
                mainCount++;
            }
            if ((qxMatchHistory.getResult() == 1 || qxMatchHistory.getResult() == 2) && qxMatchHistory.getHomeType() == 1) {
                guestCount++;
            }
        }
        if (mainCount > 3) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("主场最近强").getId());
            normalVigilance = true;
        }
        if (guestCount > 3) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("客场最近强").getId());
            normalVigilance = true;
        }
        
        qxMatchHistoryVO.setTeamid(mainTeam.getId());
        mainCount = 0;
        guestCount = 0;
        int num = 0;
        boolean flag = false;
        List<QxMatchHistory> winMatch = qxMatchHistoryService.findList(qxMatchHistoryVO);
        for (QxMatchHistory qxMatchHistory : winMatch) {
            if ((qxMatchHistory.getResult() == 3 || qxMatchHistory.getResult() == 2) && qxMatchHistory.getHomeType() == 0) {
                mainCount++;
            }
            if ((qxMatchHistory.getResult() == 3 || qxMatchHistory.getResult() == 2) && qxMatchHistory.getHomeType() == 1) {
                guestCount++;
            }
            
            //连续3场不胜
            if (qxMatchHistory.getResult() == 3 || qxMatchHistory.getResult() == 2) {
                num++;
                if (num == 3) {
                    flag = true;
                }
            } else {
                num = 0;
            }
        }
        if (mainCount > 3) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("主场最近弱").getId());
            normalVigilance = true;
        }
        if (guestCount > 3) {
            join(sBuffer, QxCacheUtils.getMontiorRuleByName("客场最近弱").getId());
            normalVigilance = true;
        }
        
        //严重警惕
        StringBuffer seriousBuffer = new StringBuffer();
        if (matchFuture.getOddsWin() >matchFuture.getOddsLose()) {
            join(seriousBuffer, QxCacheUtils.getMontiorRuleByName("赔率异常").getId());
            seriousVigilance = true;
        }
        if (mainTeam.getGuestUnusualTotal() * 1000 / mainTeam.getNormalUnusual()
                > qxDataRule.getGuestUnusualTotal() * 1000 / qxDataRule.getUnusualTotal()) {
            join(seriousBuffer, QxCacheUtils.getMontiorRuleByName("客场状态异常").getId());
            seriousVigilance = true;
        }
        
        if (mainTeam.getMainUnusualTotal() * 1000 / mainTeam.getNormalUnusual()
                > qxDataRule.getMainUnusualTotal() * 1000 / qxDataRule.getUnusualTotal()) {
            join(seriousBuffer, QxCacheUtils.getMontiorRuleByName("主场状态异常").getId());
            seriousVigilance = true;
            seriousVigilance = true;
        }
        if (guestTeam.getEvenCount()* 1000/ guestTeam.getCount() 
                > qxDataRule.getEvenCount()/ qxDataRule.getCountTotal()) {
            join(seriousBuffer, QxCacheUtils.getMontiorRuleByName("平率太高").getId());
            seriousVigilance = true;
        }
        map.put("normalVigilance", normalVigilance);
        map.put("seriousVigilance", seriousVigilance);
        map.put("normalRute", sBuffer);
        map.put("seriousRute", seriousBuffer);
        return map;
    }
}